package blog.util;

public class ByteUtils
{
	public static final int LEN_CHAR_BYTES = 2;
	public static final int LEN_INT_BYTES = 4;
	public static final int LEN_LONG_BYTES = 8;
	
	public static byte[] intToBytes(int value) {
		byte[] buf = new byte[LEN_INT_BYTES];
		buf[0] = (byte) (value >>> 24);
		buf[1] = (byte) (value >>> 16);
		buf[2] = (byte) (value >>> 8);
		buf[3] = (byte) value;
		return buf;
	}
	
	public static byte[] longToBytes(long value) {
		byte[] buf = new byte[LEN_LONG_BYTES];
		buf[0] = (byte) (value >>> 56);
		buf[1] = (byte) (value >>> 48);
		buf[2] = (byte) (value >>> 40);
		buf[3] = (byte) (value >>> 32);
		buf[4] = (byte) (value >>> 24);
		buf[5] = (byte) (value >>> 16);
		buf[6] = (byte) (value >>> 8);
		buf[7] = (byte) value;
		return buf;
	}
	
	public static void charToBytes(char value, byte[] buf, int offset) {
		buf[offset] = (byte) (value >>> 8);
		buf[offset + 1] = (byte) value;
	}
	
	public static long bytesToLong(byte[] buf) {
		long result = 0;
		for (int i = 0; i < 8; i++) {
			result |= ((long) (buf[i] & 0xFF)) << (8 * (7 - i));
		}
		return result;
	}

	public static int bytesToInt(byte[] buf) {
		return ((buf[0] & 0xFF) << 24) | ((buf[1] & 0xFF) << 16)
				| ((buf[2] & 0xFF) << 8) | (buf[3] & 0xFF);
	}

	public static char bytesToChar(byte[] buf)
	{
		return (char) (((buf[0] & 0xFF) << 8) | (buf[1] & 0xFF));
	}

}
